//
//  ViewController.swift
//  002
//
//  Created by YYY on 2017/9/19.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var tf1: UITextField?
    var tf2: UITextField?
    
    var result: UILabel?
    
    
    
    //可选闭包
    var completionBlock: (()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupUI()
        
        //闭包引用了self
//        test1 { [weak self] in
//            print(self?.view)
//        }
    }
    func test1(completion: @escaping()->())
    {
        //使用属性记录闭包值，self引用闭包
        completionBlock = completion
        
        DispatchQueue.global().async {
            //睡眠
            Thread.sleep(forTimeInterval: 2.0)
            DispatchQueue.main.async(execute: { 
                print("UI刷新")
                //闭包回调
                completion()
            })
        }
    }
    
    func setupUI()
    {
        
        let textfield1 = UITextField(frame: CGRect(x: 20, y: 100, width: 100, height: 30), placeholder: "0", fontSize: 14)
        
        view.addSubview(textfield1)
        tf1 = textfield1
        
        //修改变量名 command + control + e
        let textfield2 = UITextField(frame: CGRect(x: 140, y: 100, width: 100, height: 30),
                                     placeholder: "0")
        view.addSubview(textfield2)
        tf2 = textfield2
        
        let label1 = UILabel(frame: CGRect(x: 130, y: 100, width: 10, height: 30))
        label1.text = "+"
        view.addSubview(label1)
        
        let label2 = UILabel(frame: CGRect(x: 250, y: 100, width: 20, height: 30))
        label2.text = "="
        view.addSubview(label2)
        
        let label3 = UILabel(frame: CGRect(x: 270, y: 100, width: 50, height: 30))
        label3.text = "结果"
        view.addSubview(label3)
        result = label3
        
        let btn = UIButton(title: "计算")
        btn.center = view.center
       
        btn.addTarget(self, action: #selector(click), for: .touchUpInside)
        view.addSubview(btn)
        btn.sizeToFit()
        
    }
    
    func click()
    {
        print(#function)
        let str1 = Int(tf1?.text ?? "0")
        let str2 = Int(tf2?.text ?? "0")
        
        guard let num1 = str1,
            let num2 = str2 else {
            print("输入的必须是数字")
                return
        }
        
        result?.text = "\(num1+num2)"
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

